package com.cat.binaryAnswer;
/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-candies-allocated-to-k-children/
 * @create 2025/8/11 17:44
 * @since JDK17
 */

public class Solution10 {
    public boolean check(int[] candies, long k, int target) {
        long sum = 0;
        int n = candies.length;
        for (int i = 0; i < n; i++) {
            sum += candies[i] / target;
        }
        return sum >= k;
    }
    public int maximumCandies(int[] candies, long k) {
        int n = candies.length, max = candies[0];
        long sum = candies[0];
        for (int i = 1; i < n; i++) {
            max = Math.min(max, candies[i]);
            sum += candies[i];
        }
        if (sum < k) {
            return 0;
        }
        int l = 0, r = max + 1, mid;
        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (check(candies, k, mid)) {
                l = mid;
            } else {
                r = mid;
            }
        }
        return l;
    }
}
